﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Bussiness.Manager;
using Bussiness.Entity;
using ComExcel = Microsoft.Office.Interop.Excel;
namespace DSC
{
    public partial class SynchroDataPTMV : AfUserControl
    {
        public SynchroDataPTMV()
        {
            InitializeComponent();
            date.Value = PT_PTMV_HistoryManager.CreateInstant().getLastDate().AddDays(1);
        }

        private void btView_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang load dữ liệu");
            DataTable dt = PT_ToolInBillManager.CreateInstant().ViewSynchroData(date.Value);
            gridViewPTMV.DataSource = dt;
            EndShowStatusBar();
        }

        private void btImport_Click(object sender, EventArgs e)
        {
            PT_PTMV_HistoryEntity option = new PT_PTMV_HistoryEntity();
            option.IsDeleted = false;
            option.STOCK_OUT_DAT = date.Value.ToString("yyyyMMdd");
            
            if (PT_PTMV_HistoryManager.CreateInstant().SelectWithCondition(option).Rows.Count > 0)
            {
                if (MessageBox.Show("Dữ liệu ngày này đã được đồng bộ. Bạn có muốn đồng bộ lại dữ liệu cho ngày này? (Chú ý: dữ liệu cũ sẽ bị thay thế hoàn toàn bằng dữ liệu mới)", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    ShowStatusBar("Đang đồng bộ phụ tùng mang về");
                    PT_PTMVManager.CreateInstant().DeleteBySTOCK_OUT_DAT(date.Value.ToString("yyyyMMdd"));
                }
            }

            string message = PT_ToolInBillManager.CreateInstant().SynchroData(date.Value, SessionLogin.UserCode);

            if (!string.IsNullOrEmpty(message))
            {
                MessageBox.Show(message);
            }
            else
                MessageBox.Show("Đồng bộ dữ liệu thành công");
            EndShowStatusBar();
        }

        private void btExcel_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang xuất dữ liệu excel");
            DataTable dt = new DataTable();
            dt.Columns.Add("STT");
            dt.Columns.Add("NgayXuat");
            dt.Columns.Add("SoPhieu");
            dt.Columns.Add("MaPhuTung");
            dt.Columns.Add("SoLuong");
            dt.Columns.Add("Gia");
            dt.Columns.Add("SoTienGiamGia");
            dt.Columns.Add("ThanhTien");
            dt.Columns.Add("Loai");
            DataRow dr = null;

            for (int i = 0; i < gridViewPTMV.Rows.Count; i++)
            {
                dr = dt.NewRow();
                dr["STT"] = (i + 1).ToString();
                dr["NgayXuat"] = gridViewPTMV.Rows[i].Cells["STOCK_OUT_DAT"].Value.ToString();
                dr["SoPhieu"] = gridViewPTMV.Rows[i].Cells["ORDER_NO"].Value.ToString();
                dr["MaPhuTung"] = gridViewPTMV.Rows[i].Cells["PART_NO"].Value.ToString();
                dr["SoLuong"] = gridViewPTMV.Rows[i].Cells["QTY"].Value.ToString();
                dr["Gia"] = gridViewPTMV.Rows[i].Cells["PRICE"].Value.ToString();
                dr["SoTienGiamGia"] = gridViewPTMV.Rows[i].Cells["DISCOUNT_AMNT"].Value.ToString();
                dr["ThanhTien"] = gridViewPTMV.Rows[i].Cells["TotalMoney"].Value.ToString();
                dr["Loai"] = gridViewPTMV.Rows[i].Cells["ToolType"].Value.ToString();
                dt.Rows.Add(dr);
            }

            saveFileExcel.FileName = "PhuTungMangVe_" + date.Value.ToString("dd_MM_yyyy") + ".xls";
            saveFileExcel.DefaultExt = "xls";
            saveFileExcel.Filter = "Excel 2003 Files(*.xls)|*.xls|Excel 2007(*.xlsx)|*.xlsx|All Files|*.*";
            saveFileExcel.AddExtension = true;
            saveFileExcel.RestoreDirectory = true;
            saveFileExcel.Title = "Chọn đường dẫn lưu file";
            saveFileExcel.InitialDirectory = @"C:/";
            if (saveFileExcel.ShowDialog() == DialogResult.OK)
            {
                if (saveFileExcel.FileName.Split('\\')[saveFileExcel.FileName.Split('\\').Length - 1] == ".xls")
                {
                    MessageBox.Show("Nhập tên file cần lưu");
                }
                else
                {
                    // Khoi dong Excel
                    ComExcel.Application exApp = new ComExcel.Application();

                    //// them file temp xls moi
                    //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);

                    // Mo mot file Excel co san
                    //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);
                    ComExcel.Workbook exBook = exApp.Workbooks.Add(Application.StartupPath + "/ExcelTemplate/PTMV.xls");

                    // Lay sheet 1
                    ComExcel.Worksheet exSheet = (ComExcel.Worksheet)exBook.Worksheets[1];
                    //exSheet.Activate();

                    ////cau hình chung
                    //ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[8, 1], exSheet.Cells[8 + dt.Rows.Count, HondaTypeList.Count]);
                    //rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                    //rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                    //rng.VerticalAlignment = ComExcel.XlVAlign.xlVAlignCenter;
                    //rng.HorizontalAlignment = ComExcel.XlHAlign.xlHAlignCenter;
                    ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[5, 1], exSheet.Cells[gridViewPTMV.Rows.Count + 5, 9]);
                    rng.Font.Size = 9;
                    rng.WrapText = true;

                    exSheet.Cells[2, 2] = "PHỤ TÙNG MANG VỀ - " + date.Value.ToString("dd/MM/yyyy");

                    // đổ dữ liệu
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[5 + i, 1], exSheet.Cells[5 + i, 9]);
                        rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                        rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                        rng.VerticalAlignment = ComExcel.XlVAlign.xlVAlignCenter;
                        rng.HorizontalAlignment = ComExcel.XlHAlign.xlHAlignCenter;

                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            exSheet.Cells[5 + i, j + 1] = dt.Rows[i][j].ToString();
                        }
                    }

                    exBook.SaveAs(saveFileExcel.FileName, ComExcel.XlFileFormat.xlWorkbookNormal, null, null, false, false, ComExcel.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false);
                    DialogResult dlg = MessageBox.Show("File Excel được lưu ở đường dẫn sau: " + saveFileExcel.FileName + Environment.NewLine + "Bạn có muốn mở file không ?", "Thông Báo", MessageBoxButtons.YesNo);
                    if (dlg == DialogResult.Yes)
                    {
                        // hien thi chuong trinh excel
                        exApp.Visible = true;
                        exBook.ReadOnlyRecommended = false;
                    }
                    else
                    {
                        exBook.Close(false, false, false);
                        exApp.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                    }
                }
            }
            EndShowStatusBar();
        }
    }
}
